package com.ymttest.business.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import com.ymatou.iapi.hunter.paramater.LoginBindingRelationRequest;
import com.ymatou.iapi.hunter.paramater.OnBindingTempRelationEventRequest;
import com.ymatou.iapi.hunter.paramater.UpdateHunterStatusRequest;
import com.ymatou.iapi.hunter.service.LoginBindingRelationCall;
import com.ymatou.iapi.hunter.service.OnBindingTempRelationEventCall;
import com.ymatou.iapi.hunter.service.UpdateHunterStatusCall;
import com.ymatou.iapi.optrade.parameter.enums.CancelOrderTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.req.AgreeRefundReq;
import com.ymatou.iapi.optrade.parameter.req.ApplyRefundReq;
import com.ymatou.iapi.optrade.parameter.vo.SalesRefundInfoVo;
import com.ymatou.iapi.optrade.resp.Order;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.optrade.service.AgreeRefundCall;
import com.ymatou.iapi.optrade.service.RefundService;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.YMTTrading.TradingPlaceHunterOrderCallService;
import com.ymttest.database.model.hunter.HunterRelation;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.database.sqlwapper.hunter.HunterRelationWrapper;
import com.ymttest.utils.TestDataManager;

public class HunterCallService {

	private static AgreeRefundReq salesrefundsuccessReq = new AgreeRefundReq();
	private static AgreeRefundCall salesrefundsuccessCall = new AgreeRefundCall();
	
	private static LoginBindingRelationRequest loginBindingRelationRequest = new LoginBindingRelationRequest();
	private static LoginBindingRelationCall loginBindingRelationCall = new LoginBindingRelationCall();

	static int total = 0;

	/**
	 * 
	 * @param order
	 * @param agreeRefund
	 *            是否同意退款
	 * @param refundNum
	 *            商品退货数量(0代表全部退款)
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void hunterOrderRefund(Order order, boolean agreeRefund,
			int refundNum) throws ClientProtocolException, IOException {

		long orderId = order.getOrderId();

		// 申请退款
		ApplyRefundReq applyRefundReq = RefundService.applyRefund(order,
				refundNum);

		if (agreeRefund) {

			salesrefundsuccessReq.setOrderId(orderId);

			int i = 0;

			for (SalesRefundInfoVo salesRefundInfoVo : applyRefundReq
					.getSalesRefundInfoList()) {

				salesrefundsuccessReq.setRefundBillNo(salesRefundInfoVo
						.getRefundBillNo());
				salesrefundsuccessCall.setData(salesrefundsuccessReq);

				Logger.comment(String.format("orderid: %s 第 %s 个商品 退款执行",
						orderId, i + 1));

				salesrefundsuccessCall.callService();

				Logger.verifyEquals("true",
						salesrefundsuccessCall.getString("success"),
						"验证退货退款成功返回");
				i++;
			}
		}
	}

	/**
	 * 绑定临时关系
	 * 
	 * @param hunterId
	 *            推手id
	 * @param weixinId
	 *            weixinId
	 * @return
	 */
	public static void bindTempRelation(long hunterId, String weixinId)
			throws ClientProtocolException, IOException {

		OnBindingTempRelationEventRequest req = new OnBindingTempRelationEventRequest();
		OnBindingTempRelationEventCall call = new OnBindingTempRelationEventCall();

		req.setHunterId(hunterId);
		req.setWeixinId(weixinId);

		call.setData(req);
		call.callService();

		String code = call.getCode();

		if (!code.equals("ok")) {
			Logger.comment(String.format("临时绑定关系失败", code));
		}
	}

	/**
	 * 更新买手状态
	 * 
	 * @param hunterId
	 *            推手id
	 * @param status
	 *            状态值
	 * @return
	 */
	public static void updateHunter(long hunterId, int status)
			throws ClientProtocolException, IOException, JSONException {

		UpdateHunterStatusCall call = new UpdateHunterStatusCall();
		UpdateHunterStatusRequest req = new UpdateHunterStatusRequest();

		req.setHunterId(hunterId);
		req.setStatus(status);

		call.setData(req);
		call.callService();

		int code = call.getResponseData().getInt("resultCode");

		if (code != 0) {
			Logger.comment(String.format("更新买手状态失败", code));
		}
	}

	/**
	 * 更新买手状态
	 * 
	 * @param hunterId
	 *            推手id
	 * @param status
	 *            状态值
	 * @return
	 */
	public static void updateHunterLevel(long hunterId, int level)
			throws ClientProtocolException, IOException, JSONException {

		UpdateHunterStatusCall call = new UpdateHunterStatusCall();
		UpdateHunterStatusRequest req = new UpdateHunterStatusRequest();

		req.setHunterId(hunterId);
		req.setStatus(level);

		call.setData(req);
		call.callService();

		int code = call.getResponseData().getInt("resultCode");

		if (code != 0) {
			Logger.comment(String.format("更新买手状态失败", code));
		}
	}

	/**
	 * 构建买手关系，num为多个人的时候，关系为a<b<c
	 * 
	 * @param level
	 *            推手等级（0：普通买家，1：推手，2：服务商，3：金牌服务商  4：合伙人）
	 * @param num
	 *            推手数量
	 * @param parent_hunter_id
	 *            上级推手id
	 * @return hunterId 返回推手Id列表
	 */
	public static List<Long> buildHunterRelation(int level, int num,
			long parent_hunter_id) {
		try {
			HunterRelationWrapper wrapper = new HunterRelationWrapper();
			HunterRelation hunterRelation = null;
			long hunterId = 0L;
			List<Long> hunterList = new ArrayList<Long>();

			for (int i = 0; i < num; i++) {

				int userId = new OrderCallService().createNewUser();

				hunterRelation = new HunterRelation();
				hunterId = Long
						.valueOf(userId);

				hunterRelation.setAdd_time(new Date());
				hunterRelation.setUpdate_time(new Date());
				hunterRelation.setHunter_id(hunterId);
				hunterRelation.setHunter_level(level);
				hunterRelation.setHunter_name("autohunter" + hunterId);
				hunterRelation.setParent_hunter_id(parent_hunter_id);
				hunterRelation.setStatus(0);
//				hunterRelation.setCode(TestDataManager.getRandomUUID().toString().substring(0, 5));
				hunterRelation.setChildren_total(0);

				// 将上一次的hunterId作为下个推手的上级
				parent_hunter_id = hunterId;

				wrapper.insert(hunterRelation);

				hunterList.add(hunterId);
			}

			return hunterList;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return new ArrayList<Long>();
		}
	}

	/**
	 * 用户购买某个hunter的大礼包
	 * 
	 * @param userId
	 * @param hunterId
	 * @throws Exception
	 */
	public static void buyHunterGiftBagOrder(long userId, long hunterId)
			throws Exception {

		OrderShardingWapper orderShardingWapper = new OrderShardingWapper();
		List<OrderPo> orderList = orderShardingWapper
				.selectHunterGiftBagOrderbyUserId(userId);

		if (orderList.size() > 0) {
			for (OrderPo po : orderList) {
				TradingCallService.cancelOrder(po.getOrderId(),
						CancelOrderTypeEnum.BUYER_CANCEL_ORDER, userId);
			}
		}

		TradingServiceResp placeOrder = TradingPlaceHunterOrderCallService.placeHunterOrder(
				hunterId, userId, 1);

		long sellerId = placeOrder.getOrderList().get(0).getSellerId();
		long orderId = placeOrder.getOrderList().get(0).getOrderId();
		long tradingId = placeOrder.getTradingId();
		BigDecimal totalPrice = placeOrder.getPayableAmount();

		Long thirdTradingId = TradingCallService.payOrder(userId,
				BigDecimal.ZERO, tradingId, "13");

		PayGateWayCallService.notifyCall("13", thirdTradingId.toString(),
				totalPrice.subtract(BigDecimal.ZERO).toString(), (int) userId);
		TradingSyncService.getSyncResult(orderId);
		Thread.sleep(5000);

		int orderStatus = orderShardingWapper.selectOrderbyOrderId(orderId)
				.getOrderStatus();

		// 如果订单支付后没有自动接单，尝试手动接单
		if (orderStatus == 2) {

			TradingCallService.sellerAcceptOrder(sellerId, orderId);
			TradingSyncService.getSyncResult(orderId);
		}

		// 拼邮国际段发货
		TradingCallService.delivery(sellerId, orderId,
				LogisticsTypeEnum.PackageDelivery, 1);
		TradingSyncService.getSyncResult(orderId);
		// 拼邮国内段发货
		TradingCallService.delivery(sellerId, orderId,
				LogisticsTypeEnum.PackageDelivery, 3);

		TradingCallService.confirmReceive(userId, orderId);
	}

	/**
	 * 佣金结算
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void doCommissionSettlement() throws ClientProtocolException,
			IOException {

		Logger.comment("开始执行doCommissionSettlement");

		YmatouEasyCall doCommissionSettlementCall = new YmatouEasyCall("", "POST",
				"JSON");
		StringBuffer doCommissionSettlementString = new StringBuffer();

		doCommissionSettlementString.append("{}");
		doCommissionSettlementCall
				.setUrl("http://tradingsettlement.iapi.ymatou.com/api/doCommissionSettlement");
		doCommissionSettlementCall.setData(doCommissionSettlementString.toString());

		doCommissionSettlementCall.callService();

		if (doCommissionSettlementCall.getReturnData().equalsIgnoreCase("ok"))
			Logger.comment("调用doCommissionSettlement成功");
		else
			Logger.comment("调用doCommissionSettlement失败");
	}

	/**
	 * 生成结算单
	 * 
	 * @param orderId
	 * @param sellerId
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void onOrderPaid(long orderId, long hunterOrderType, long buyerId, long hunterId)
			throws ClientProtocolException, IOException {

		Logger.comment("开始执行onOrderPaid");

		YmatouEasyCall onOrderPaidCall= new YmatouEasyCall("", "POST",
				"JSON");
		StringBuffer onOrderPaidString = new StringBuffer();

		onOrderPaidString.append("{\"OrderId\":" + orderId + ",");
		onOrderPaidString.append("\"BuyerId\":" + buyerId + ",\"appId\":\"optrade.iapi.ymatou.com\",\"BusinessType\":2,\"ParamExt\":{},\"SellerId\":20336378,\"UserLoginName\":\"autotest_Dw8x9EvLqS\",");
		onOrderPaidString.append("\"HunterOrderType\":" + hunterOrderType + ", \"HunterId\":" + hunterId + "}");
		onOrderPaidCall
				.setUrl("http://tradingsettlement.iapi.ymatou.com/api/onOrderPaid");
		onOrderPaidCall.setData(onOrderPaidString.toString());

		onOrderPaidCall.callService();

		if (onOrderPaidCall.getReturnData().equalsIgnoreCase("ok"))
			Logger.comment("调用onOrderPaid成功");
		else
			Logger.comment("调用onOrderPaid失败");
	}

	/**
	 * 累计订单对应推手销售总金额
	 * 
	 * @param orderId
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void sumOrderSalesAmount(long orderId)
			throws ClientProtocolException, IOException {

		Logger.comment("开始执行sumOrderSalesAmount");

		YmatouEasyCall sumOrderSalesAmountCall = new YmatouEasyCall("", "POST",
				"JSON");
		StringBuffer sumOrderSalesAmountString = new StringBuffer();

		sumOrderSalesAmountString.append("{\"orderId\":" + orderId + "}");
		sumOrderSalesAmountCall
				.setUrl("http://tradingsettlement.iapi.ymatou.com/api/sumOrderSalesAmount");
		sumOrderSalesAmountCall.setData(sumOrderSalesAmountString.toString());

		sumOrderSalesAmountCall.callService();

		if (sumOrderSalesAmountCall.getReturnData().equalsIgnoreCase("ok"))
			Logger.comment("调用sumOrderSalesAmount成功");
		else
			Logger.comment("调用sumOrderSalesAmount失败");
	}
	
	/**
	 * 计算服务商之间的管理费
	 * 
	 * @param orderId
	 * @param hunterId
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static void onHunterRelationSearchedForManageFee(long orderId,
			long hunterId) throws ClientProtocolException, IOException {

		Logger.comment("开始执行onHunterRelationSearchedForManageFee");

		YmatouEasyCall onHunterRelationSearchedForManageFeeCall = new YmatouEasyCall(
				"", "POST", "JSON");
		StringBuffer onHunterRelationSearchedForManageFeeString = new StringBuffer();

		onHunterRelationSearchedForManageFeeString.append("{\"orderId\":"
				+ orderId + ",");
		onHunterRelationSearchedForManageFeeString.append("\"hunterId\":"
				+ hunterId + "}");
		onHunterRelationSearchedForManageFeeCall
				.setUrl("http://tradingsettlement.iapi.ymatou.com/api/onHunterRelationSearchedForManageFee");
		onHunterRelationSearchedForManageFeeCall
				.setData(onHunterRelationSearchedForManageFeeString.toString());

		onHunterRelationSearchedForManageFeeCall.callService();

		if (onHunterRelationSearchedForManageFeeCall.getReturnData()
				.equalsIgnoreCase("ok"))
			Logger.comment("调用onHunterRelationSearchedForManageFee成功");
		else
			Logger.comment("调用onHunterRelationSearchedForManageFee失败");
	}

	/**
	 * 获得当前hunterId的团队人数
	 * 
	 * @param hunterId
	 * @return
	 */
	public static int countChildren(long hunterId, boolean start) {

		if (start)
			total = 0;

		HunterRelationWrapper wrapper = new HunterRelationWrapper();
		List<HunterRelation> hunterRelationList = wrapper
				.selectSubordinateByHunterId(hunterId);

		if (hunterRelationList == null)
			return 0;
		else
			total += hunterRelationList.size();

		for (HunterRelation hunterRelation : hunterRelationList) {
			countChildren(hunterRelation.getHunter_id(), false);
		}

		return total;
	}

	/**
	 * 通过推手邀请码绑定永久关系
	 * 
	 * @param userId
	 * @param userName
	 * @param code
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void bingRelationByHunterCode(long userId, String userName,
			String code) throws ClientProtocolException, IOException {

		loginBindingRelationRequest.setUserId(userId);
		loginBindingRelationRequest.setUserName(userName);
		loginBindingRelationRequest.setCode(code);

		loginBindingRelationCall.setData(loginBindingRelationRequest);
		loginBindingRelationCall.callService();
	}
	
	/**
	 * 获取catalogId对应的giftType
	 * 
	 * @param catalogId
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static HashMap<String, Object> getCatalogCommissions(String catalogId) {

		Logger.comment("开始执行queryCatalogCommissions");

		YmatouEasyCall queryCatalogCommissionsCall = new YmatouEasyCall(
				"", "POST", "JSON");
		StringBuffer queryCatalogCommissionsString = new StringBuffer();
		HashMap<String, Object> map = new HashMap<>();

		queryCatalogCommissionsString.append("{\"catalogIds\":[\""
				+ catalogId + "\"]}");
		
		queryCatalogCommissionsCall
				.setUrl("http://productmanager.iapi.ymatou.com/api/SellerProduct/queryCatalogCommissions");
		queryCatalogCommissionsCall
				.setData(queryCatalogCommissionsString.toString());

		try {
			queryCatalogCommissionsCall.callService();
			
			JSONObject data = new JSONObject(
					queryCatalogCommissionsCall.getReturnData())
					.optJSONObject("Data");

			if (null == data) {

				map.put("giftType", 0);
				map.put("saleCommissionList", new JSONObject());
				map.put("newRule", null);
				map.put("saleTerminalPercent", null);
			} else {

				Logger.debug("returndata:" + data);

				int giftType = data.optJSONArray("CommissionList")
						.getJSONObject(0).optInt("GiftType");

				JSONObject saleCommissionList = data
						.optJSONArray("CommissionList").getJSONObject(0)
						.optJSONObject("SaleCommissionList");
				
				JSONObject saleCommissionMapNew = data
						.optJSONArray("CommissionList").getJSONObject(0)
						.optJSONObject("SaleCommissionMapNew");
				
				if (giftType == 1)
					map.put("saleCommissionMapNew", saleCommissionMapNew);
				
				if (saleCommissionMapNew != null) {
					
					BigDecimal saleTerminalPercent = new BigDecimal(data
							.optJSONArray("CommissionList").getJSONObject(0)
							.optString("SaleTerminalPercent"));
					
					map.put("saleTerminalPercent", saleTerminalPercent);
					map.put("newRule", true);
				} else {
					
					map.put("saleTerminalPercent", null);
					map.put("newRule", false);
				}

				map.put("giftType", giftType);
				map.put("saleCommissionList", saleCommissionList);
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return map;
	}

	public static void main(String[] args) {

//		List<Long> list = HunterCallService.buildHunterRelation(1, 5,
//				44601981000L);
//
//		for (Long l : list)
//			System.out.println(l);
		
		Logger.comment(TestDataManager.getRandomUUID().toString().substring(0, 5));
	}
}
